
package org.geometerplus.fbreader.formats.ceb;

import org.geometerplus.fbreader.book.Book;
import org.geometerplus.fbreader.bookmodel.BookModel;
import org.geometerplus.fbreader.bookmodel.BookReadingException;
import org.geometerplus.fbreader.formats.JavaFormatPlugin;
import org.geometerplus.fbreader.formats.oeb.ContainerFileReader;
import org.geometerplus.zlibrary.core.encodings.AutoEncodingCollection;
import org.geometerplus.zlibrary.core.filesystem.ZLFile;
import org.geometerplus.zlibrary.core.image.ZLImage;

import android.util.Log;

/**
 * ceb 文件的formate plugin
 * @author zouqp
 * 2014-09-28
 */

public class CEBPlugin extends JavaFormatPlugin {
	public CEBPlugin(String fileType) {
		super(fileType);
	}

	private ZLFile getOpfFile(ZLFile cebFile) throws BookReadingException {
		if ("opf".equals(cebFile.getExtension())) {
			return cebFile;
		}
		
		if ("ncx".equals(cebFile.getExtension())) {
			return cebFile;
		}

		final ZLFile containerInfoFile = ZLFile.createFile(cebFile, "container.xml");
		if (containerInfoFile.exists()) {
			final ContainerFileReader reader = new ContainerFileReader();
			reader.readQuietly(containerInfoFile);
			String opfPath = reader.getRootPath();
			if (opfPath != null) {
				opfPath = opfPath.substring(opfPath.lastIndexOf("/") + 1);
				return ZLFile.createFile(cebFile, opfPath);
			}
		}

		for (ZLFile child : cebFile.children()) {
			if (child.getExtension().equals("opf")) {
				return child;
			}
		}
		throw new BookReadingException("opfFileNotFound", cebFile);
	}

	@Override
	public void readMetaInfo(Book book) throws BookReadingException {
		new CEBMetaInfoReader(book).readMetaInfo(getOpfFile(book.File));
	}

	@Override
	public void readUids(Book book) throws BookReadingException {
		// this method does nothing, we expect it will be never called
	}

	@Override
	public void readModel(BookModel model) throws BookReadingException {
		model.Book.File.setCached(true);
		new CEBBookReader(model).readBook(getOpfFile(model.Book.File));
	}
	
	@Override
	public void readChapter(BookModel model, String chapterid) throws BookReadingException { 
		new CEBBookReader(model).readChapter(getOpfFile(model.Book.File), chapterid);
	}
	
	@Override
	public ZLImage readCover(ZLFile file) {
		return null;
		/*
		try {
			return new OEBCoverReader().readCover(getOpfFile(file));
		} catch (BookReadingException e) {
			return null;
		}
		*/
	}

	@Override
	public String readAnnotation(ZLFile file) {
		return "";
		/*
		try {
			return new OEBAnnotationReader().readAnnotation(getOpfFile(file));
		} catch (BookReadingException e) {
			return null;
		}*/
	}

	@Override
	public AutoEncodingCollection supportedEncodings() {
		return new AutoEncodingCollection();
	}

	@Override
	public void detectLanguageAndEncoding(Book book) {
		book.setEncoding("auto");
	}
}
